import React, { Component } from 'react'
import { withRouter } from 'react-router'
import { Modal } from 'antd';

import menuList from '../../config/menuConfig'
import { formateDate } from '../../utils/dateUtils'
import { reqWeather } from '../../api/index'
import memoryUtils from '../../utils/memoryUtils'
import storageUtils from '../../utils/storageUtils'
import LinkButton from '../link-button';
import './index.less'

// 后台管理的路由组件
class Header extends Component {

  state = {
    currentTime: formateDate(Date.now()), // 当前时间字符串
    weather: '' // 天气的文本
  }

  getTime = () => {
    // 每隔1s获取当前时间，并更新状态数据currentTime
    this.interval = setInterval(() => {
      const currentTime = formateDate(Date.now())
      this.setState({ currentTime })
    }, 1000)
  }

  getweather = async () => {
    const weather = await reqWeather()
    this.setState({ weather })
  }

  getTitle = () => {
    // 得到当前请求路径
    const path = this.props.location.pathname
    let title
    menuList.forEach(item => {
      if (item.key === path) { // 如果当前item对象的key与path一样，item的title就是需要显示的title
        title = item.title
      } else if (item.children) {
        // 在所有的子item中查找匹配的
        const cItem = item.children.find(cItem => cItem.key === path)
        if (cItem) { // 如果有值才说明有匹配的
          // 取出它的title
          title = cItem.title;
        }
      }
    })
    return title
  }

  // 退出登录
  logout = () => {
    // 显示对话框
    Modal.confirm({
      content: '确定退出吗？',
      onOk: () => {
        storageUtils.removeUser();
        memoryUtils.user = {};
        
        this.props.history.replace('/login')
      }
    });
  }

  // 第一次render()之后执行
  // 一般在此执行异步操作：发ajax请求 / 启动定时器
  componentDidMount() {
    // 获取当前时间
    this.getTime()
    // 获取当前天气
    this.getweather()
  }

  // 当前组件卸载之前调用
  componentWillUnmount() {
    // 清除定时器
    clearInterval(this.interval)
  }

  username = memoryUtils.user.username

  render() {
    const { currentTime, weather } = this.state
    const title = this.getTitle()

    return (
      <div className="header">
        <div className="header-top">
          <span>欢迎，{this.username}</span>
          <LinkButton onClick={this.logout}>退出</LinkButton>
        </div>
        <div className="header-bottom">
          <div className="header-bottom-left">{title}</div>
          <div className="header-bottom-right">
            <span>{currentTime}</span>
            <span className="weather">{weather}</span>
          </div>
        </div>
      </div>
    )
  }
}

export default withRouter(Header)